package com.hc.controller;

import com.hc.util.JsonResponse;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;

@RestController
@RequestMapping("/FileUploadLoadController")
@CrossOrigin
public class FileUploadLoadController {


   /* 用户名:<input name="username"><br/>
    密码:<input name="password"><br/>

    文件：<input type="file" name="photo"></input>*/


    @PostMapping("/uploadFile")
    public JsonResponse uploadFile(String username, String password, MultipartFile photo){
        JsonResponse jsonResponse = new JsonResponse();
        if (photo!=null){
             String fileName =  photo.getOriginalFilename();//获取文件名
            String contentType =      photo.getContentType() ;    //获取文件类型
            try {
              //  byte[] fileCOntent =  photo.getBytes();//获取文件字节数组
                System.out.println("文件名:"+fileName);
                System.out.println("contentType:"+contentType);
               // System.out.println("文件字节数组:"+ Arrays.toString(fileCOntent));

                String savePath = "D:\\apache-tomcat-9.0.106-windows-x64\\apache-tomcat-9.0.106\\webapps\\images";
                File dir = new File(savePath);
                if (!dir.exists()){
                    dir.mkdirs();   //
                    System.out.println("创建目录:"+savePath);
                }

                File saveFile = new File(dir,fileName);//文件保存的位置
                photo.transferTo(saveFile);

                jsonResponse.setData("http://192.168.116.6:8080/images/"+fileName);
             //   FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
              //  fileOutputStream.write(fileCOntent);


            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return  jsonResponse;
    }
}
